package com.metadata_system.api.inspect;


import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.metadata_system.common.dto.ApiResult;
import com.metadata_system.common.exception.ApiException;
import com.metadata_system.common.exception.ApiSignException;
import com.metadata_system.common.utils.AesUtils;
import com.metadata_system.common.utils.ApiSignUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;


@Aspect
@Configuration
@Slf4j
public class ApiCheckInterceptor {


    @SneakyThrows
    @Around("execution(public * *(..)) && @annotation(com.metadata_system.api.annotations.ApiCheckSign)")
    public Object interceptor(ProceedingJoinPoint pjp) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        // 1.获取 request
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        try {
            if (StringUtils.isBlank(request.getHeader("DeviceId"))){
                throw new ApiException("非法数据 1");
            }
            String str= AesUtils.Decrypt(request.getHeader("DeviceId"));
        }catch (Exception e){
            e.printStackTrace();
            throw new ApiException("非法数据 3");
        }

        ApiResult apiResult = ApiSignUtils.checkSign(request.getRequestURI(), request.getHeader("Deviceid"), request.getHeader("Timestamp"), request.getHeader("Sign"),request.getParameterMap());
        if (apiResult.getCode()>0){
            throw new ApiSignException(apiResult.getMessage());
        }
        return pjp.proceed();
    }




}
